#pragma once
#include <functional>
#include <poll.h>
#include "sock.hpp"

namespace poll_ns
{
    static const int defaultport = 8081;
    static const int defaultfd = -1;
    static const int num = 2048;

    using func_t = std::function<std::string(const std::string &)>;
    class PollServer
    {
    private:
        int _port;
        int _listensock;
        struct pollfd *_rfds; // 结构体数组
        func_t _func;

    public:
        PollServer(func_t func, uint16_t port = defaultport)
            : _port(port),
              _listensock(-1),
              _rfds(nullptr),
              _func(func)
        {
        }
        void reset(int i)
        {
            _rfds[i].fd = defaultfd;
            _rfds[i].events = 0;
            _rfds[i].revents = 0;
        }
        void initServer()
        {
            _listensock = Sock::Socket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);
            _rfds = new struct pollfd[num];
            for (int i = 0; i < num; ++i)
                reset(i);
            _rfds[0].fd = _listensock; // 固定不变了
            _rfds[0].events = POLLIN;  // 关心读事件
            logMessage(NORMAL, "create listen sock success %d\n", _listensock);
        }

        void start()
        {
            // 单位是ms
            int time = 2000; // 0立即返回 >0等time时间返回 -1阻塞等待
            while (1)
            {
                int n = poll(_rfds, num, time);
                switch (n)
                {
                case 0: // 超时返回
                    logMessage(NORMAL, "timeOut...");
                    break;
                case -1: // 失败
                    logMessage(WARNING, "poll error, code: %d, err string:%s", errno, strerror(errno));
                    break;
                default:
                    // 事件就绪 -- 目前只有监听事件就绪了
                    logMessage(NORMAL, "have event ready");
                    handlerReadEvent();
                    break;
                }
            }
        }
        void handlerReadEvent()
        {
            for (int i = 0; i < num; ++i)
            {
                // 非法
                if (_rfds[i].fd == defaultfd)
                    continue;
                // 没有关心该fd的读事件
                if (!(_rfds[i].events & POLLIN))
                    continue;
                // 合法且关心了读事件
                // 但未必就绪
                if (_rfds[i].fd == _listensock && (_rfds[i].revents & POLLIN))
                {
                    Accepter(_listensock);
                }
                else if (_rfds[i].revents & POLLIN)
                {
                    Reader(i);
                }
            }
        }
        void Accepter(int listensock)
        {
            // 走到这里 accept系统调用一定不会阻塞
            // listensock的读事件一定就绪
            std::string clientip;
            uint16_t clientport = -1;
            int sock = Sock::Accept(listensock, &clientip, &clientport);
            if (sock < 0)
                return;
            int i = 0;
            while (i < num && _rfds[i].fd != defaultfd)
            {
                ++i;
            }
            if (i == num)
            {
                logMessage(WARNING, "Server is full");
                close(sock);
                return;
            }
            else
            {
                _rfds[i].fd = sock;
                _rfds[i].events = POLLIN;
                _rfds[i].revents = 0;
            }
        }
        void Reader(int pos)
        {
            // 直接读固定大小是有问题的，不能保证读到一个完整报文
            char buffer[1024];
            ssize_t s = recv(_rfds[pos].fd, buffer, sizeof(buffer) - 1, 0);
            if (s > 0)
            {
                buffer[s] = 0;
                logMessage(NORMAL, "client #: %s", buffer);
            }
            else if (s == 0)
            {
                close(_rfds[pos].fd);
                reset(pos);
                logMessage(NORMAL, "client quit");
                return;
            }
            else
            {
                close(_rfds[pos].fd);
                reset(pos);
                logMessage(ERROR, "error string: %s", strerror(errno));
                return;
            }
        std:
            std::string response = _func(buffer);
            response += '\n';
            // 写事件，有问题的，需要重新维护一个写就绪的文件描述符数组 _wfds
            write(_rfds[pos].fd, response.c_str(), response.size());
        }

        ~PollServer()
        {
            if (_listensock > 0)
            {
                close(_listensock);
            }
            if (_rfds)
            {
                delete[] _rfds;
            }
        }
    };
}